package servlet.home;

import com.sun.mail.util.MailSSLSocketFactory;
import servlet.Control;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Properties;

@WebServlet(name = "SendEmail",value = "/home/sendEmail")
public class SendEmail extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("name");
        String email=request.getParameter("email");
        String message=request.getParameter("message");

        StringBuffer buffer=new StringBuffer("");
        buffer.append("name:  "+name+"\n\n");
        buffer.append("email:  "+email+"\n\n");
        buffer.append("message:  "+message);

        //开启一个发送信息的线程，这样就不需要让客户等待
        Thread thread=new Send(buffer.toString(),name);
        thread.start();

        Control.success(response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }


    private class Send extends Thread{
        private String text;
        private String title;

        public Send(String text,String title){
            this.text=text;
            this.title=title;
        }

        @Override
        public void run() {
            sendEmail(text,title);
        }
    }

    private static void sendEmail(String text,String title){
        String email="interpreterinchina@163.com";
        String pwd="translation1234";

        String destination="interpreterinchina@163.com";
        try {
            Properties props=new Properties();

            //设置各种东西
            props.setProperty("mail.smtp.auth","true");
            props.setProperty("mail.host", "smtp.163.com");
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.debug", "true");

            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);

            Session session=Session.getDefaultInstance(props);

            //设置邮箱头
            Message msg=new MimeMessage(session);
            msg.setFrom(new InternetAddress(email));
            msg.setText(text);
            msg.setSubject("translator");

            //连接自己的邮箱
            Transport transport=session.getTransport();
            transport.connect("smtp.163.com",email,pwd);
            transport.sendMessage(msg,new Address[]{new InternetAddress(destination)});
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
